<?php
header("Content-type: text/xml");
function widxml($title, $content) {
	$content = str_replace("'", "\'", $content);
	$title = str_replace('"', '\"', $title);
	$ret = '<?xml version="1.0" encoding="UTF-8" ?>';
	$ret .= '<Module>';
	$ret .= '<ModulePrefs title="'.$title.'" source="Blogger Items Widgets" website="'.home_url().'/widgets"/>'; 
	$ret .= '<Content type="html">';
	$ret .= '<![CDATA[ ';
	$ret .= $content;
	$ret .= ']]>';
	$ret .= '</Content>'; 
	$ret .= '</Module>';
	return $ret;
}


function main() {
	$ret = '';
	$error = '-1';
	
	/* `get options */	
	$id = $_POST["id"];
	if ($id == '' || $id == null) {
		$id = $_GET["id"];
	}
	
	if ($id == '' || $id == null) {
		$title = $_POST["title"];
		$content = $_POST["content"];
		if ($title == '' || $title == null || $content == '' || $content == null) {
			return $error;
		}
		// add new gadget
		if (mysql_query("INSERT INTO `wp_widxml`(`title`, `content`, `timestamp`) VALUES ('".$title."','".$content."', CURRENT_TIMESTAMP)")) {
			return mysql_insert_id();
		} else {
			return $error;
		}
		
	} else {
		if (is_numeric($id)) {
			$title = $_POST["title"];
			$content = $_POST["content"];
			// Display gadget
			if ($title == '' || $title == null || $content == '' || $content == null) {
				$widxml = mysql_query('SELECT * FROM `wp_widxml` WHERE `ID`="'.$id.'"');
				if ($widxml == false) {
					return $error;
				}
				$widxml_rows = mysql_num_rows($widxml);
				if ($widxml_rows > 0) {
					$item = mysql_fetch_assoc($widxml);
					$title = $item['title'];
					$content = $item['content'];
					mysql_free_result($widxml);
					return widxml($title, $content);
				}
				else {
					return $error;
				}
				
			} 
			// update gadget
			else {
				if (mysql_query("UPDATE `wp_widxml` SET `title`='".$title."',`content`='".$content."'  WHERE `link`='".$url."'")) {
					return $id;
				} else {
					return $error;
				}
			}
		} else {
			return $error;
		}
	}
	
	return $ret;
}

echo main();

// Removing entries not updated in the last 1 hour:
mysql_query('DELETE FROM `wp_widxml` WHERE `expire`<SUBTIME(NOW(),"0 1:0:0")');

?>
